package me.zhengjie.config.apijson;

import apijson.JSONRequest;
import apijson.JSONResponse;
import apijson.RequestMethod;
import apijson.StringUtil;
import apijson.framework.APIJSONFunctionParser;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.Collection;

public class AutoFunctionParser  extends APIJSONFunctionParser {
    public int deleteCommentOfMoment(@NotNull JSONObject current, @NotNull String momentId) throws Exception {
        long mid = current.getLongValue(momentId);
        if (mid <= 0 || current.getIntValue(JSONResponse.KEY_COUNT) <= 0) {
            return 0;
        }

        JSONRequest request = new JSONRequest();

        //Comment<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        JSONRequest comment = new JSONRequest();
        comment.put("momentId", mid);

        request.put("Comment", comment);
        //Comment>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        JSONObject rp = new AutoParser(RequestMethod.DELETE).setNeedVerify(false).parseResponse(request);

        JSONObject c = rp.getJSONObject("Comment");
        return c == null ? 0 : c.getIntValue(JSONResponse.KEY_COUNT);
    }
    public Object verifyIdList(@NotNull JSONObject current, @NotNull String idList) throws Exception {
        Object obj = current.get(idList);
        if (obj == null) {
            return null;
        }

        if (obj instanceof Collection == false) {
            throw new IllegalArgumentException(idList + " 不符合 Array 类型! 结构必须是 [] ！");
        }
        JSONArray array = (JSONArray) obj;
        if (array != null) {
            for (int i = 0; i < array.size(); i++) {
                if (array.get(i) instanceof Long == false && array.get(i) instanceof Integer == false) {
                    throw new IllegalArgumentException(idList + " 内字符 " + array.getString(i) + " 不符合 Long 类型!");
                }
            }
        }
        return null;
    }
    public Object verifyURLList(@NotNull JSONObject current, @NotNull String urlList) throws Exception {
        Object obj = current.get(urlList);
        if (obj == null) {
            return null;
        }

        if (obj instanceof Collection == false) {
            throw new IllegalArgumentException(urlList + " 不符合 Array 类型! 结构必须是 [] ！");
        }
        JSONArray array = (JSONArray) obj;
        if (array != null) {
            for (int i = 0; i < array.size(); i++) {
                if (StringUtil.isUrl(array.getString(i)) == false) {
                    throw new IllegalArgumentException(urlList + " 内字符 " + array.getString(i) + " 不符合 URL 格式!");
                }
            }
        }
        return null;
    }
    public LocalDateTime getNow(@NotNull JSONObject current){
        return LocalDateTime.now();
    }
    public int getOwner(@NotNull JSONObject current){
        return 1;
    }
}